package com.example.filters;



import com.google.common.base.Stopwatch;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.MDC;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerMapping;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Component
public class PerfInterceptor extends HandlerInterceptorAdapter {
    private static final Logger logger = LoggerFactory.getLogger(PerfInterceptor.class);
    private static ThreadLocal<Stopwatch> local = new ThreadLocal<>();

    public static final String URL_KEY = "URL";
    public static final String FAIL_NAMESPACE = "api.fail";
    public static final String SUCCESS_NAMESPACE = "api.success";
    public static final String X_REQUEST_ID = "X-Request-Id";
    public static final String TRACE_ID = "traceId";


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        logger.info("执行PerfInterceptor");
        //增加uri
        String uri = (String) request.getAttribute(HandlerMapping.BEST_MATCHING_PATTERN_ATTRIBUTE);
        Stopwatch watch = Stopwatch.createStarted();
        local.set(watch);

        MDC.put(PerfInterceptor.URL_KEY, uri);

        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
        Stopwatch watch = local.get();
        if (watch != null) {

            long spentTime = watch.elapsed(TimeUnit.MILLISECONDS);
            String method = request.getMethod();
           String url =  MDC.get(PerfInterceptor.URL_KEY);
           String traceId = MDC.get(PerfInterceptor.TRACE_ID);
            logger.info("接口执行耗时："+spentTime+"毫秒,url="+url+",method="+method+",traceId="+traceId);

//            QuotaMonitor monitor = ConfigManager.get(QuotaMonitor.class);
//            String appName = monitor == null ? "UNKNOWN" : monitor.getAppName();
//            if (ex != null) {
//                PerfUtils.perf(LogConstant.FAIL_NAMESPACE, appName, request.getAttribute(HandlerMapping.BEST_MATCHING_PATTERN_ATTRIBUTE)).millis(watch.elapsed(TimeUnit.MILLISECONDS)).logstashOnly();
//            } else {
//                PerfUtils.perf(LogConstant.SUCCESS_NAMESPACE, appName, request.getAttribute(HandlerMapping.BEST_MATCHING_PATTERN_ATTRIBUTE)).millis(watch.elapsed(TimeUnit.MILLISECONDS)).logstashOnly();
//            }
        }
        local.remove();

    }
}